#include"network.h"


int main()
{
    //创建套接字
    int fd = socket(AF_INET,SOCK_DGRAM,0);
    if(fd==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
        exit(LOG_LEVEL_SOCKET);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"socket is successful!");
    }

    //绑定IP和端口
    struct sockaddr_in local;
    local.sin_family=AF_INET;
    local.sin_addr.s_addr=INADDR_ANY;
    local.sin_port=htons(8000);
    memset(&local.sin_zero, 0, sizeof(local.sin_zero));
    int bd = bind(fd,(struct sockaddr *)&local,sizeof(local));
    if(fd==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
        exit(LOG_LEVEL_BIND);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"bind is successful!");
    }

    //接收数据
    char buffer[1024]={'\0'};
    struct sockaddr_in local_t;
    socklen_t sz=sizeof(local);
    while(1)
    {
        ssize_t re= recvfrom(fd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&local_t,&sz);
        if(re==-1)//根据-1来判断是错误还是没有数据
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK) 
            {
            //没有数据，稍等片刻再试
            printf("暂时没有数据，等待...\\n");
            sleep(1);
            } 
            else 
            {
                //发生其他错误，处理错误
                log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
                exit( LOG_LEVEL_RECVFROM);
            }
        }
        else
        {
            buffer[re] = 0;
            std::cout<<"读取到数据:"<<buffer<<std::endl;
        }

        //回发给对方
        std::string s("我接收到了你的数据:");
        s+=buffer;
        ssize_t ac =sendto(fd,s.c_str(),s.size(),0,(const sockaddr*)&local_t,sizeof(local_t));
        if(ac==-1)
        {
            log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
            exit(LOG_LEVEL_SENDTO);
        }
    }

    return 0;
}